package com.imut.lagain.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.imut.lagain.entity.MemoryCapsule;
import com.imut.lagain.entity.MemoryEntry;
import com.imut.lagain.service.IMemoryCapsuleService;
import com.imut.lagain.service.IMemoryEntryService;
import com.imut.lagain.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 记忆胶囊控制器
 */
@RestController
@RequestMapping("/api/capsules")
@RequiredArgsConstructor
@Validated
public class MemoryCapsuleController {
    private static final Logger log = LoggerFactory.getLogger(MemoryCapsuleController.class);

    private final IMemoryCapsuleService memoryCapsuleService;
    private final IMemoryEntryService memoryEntryService;
    private final JwtUtil jwtUtil;

    /**
     * 获取用户的胶囊列表
     * @param authorization JWT令牌
     * @param page 页码
     * @param size 每页大小
     * @param status 状态筛选
     * @return 胶囊列表
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getUserCapsules(
            @RequestHeader("Authorization") String authorization,
            @RequestParam(defaultValue = "1") @Min(1) Integer page,
            @RequestParam(defaultValue = "10") @Min(1) @Max(100) Integer size,
            @RequestParam(required = false) Integer status) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            IPage<MemoryCapsule> capsulePage;
            if (status != null) {
                capsulePage = memoryCapsuleService.getUserCapsulesByStatus(userId, status, page, size);
            } else {
                capsulePage = memoryCapsuleService.getUserCapsules(userId, page, size);
            }
            
            response.put("success", true);
            response.put("data", capsulePage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get user capsules", e);
            response.put("success", false);
            response.put("message", "获取胶囊列表失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 创建新的记忆胶囊
     * @param authorization JWT令牌
     * @param request 创建请求
     * @return 创建结果
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createCapsule(
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody CreateCapsuleRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            MemoryCapsule capsule = memoryCapsuleService.createCapsule(
                    userId,
                    request.getTitle(),
                    request.getDescription(),
                    request.getCoverImageUrl(),
                    request.getType(),
                    request.getOpenTime(),
                    request.getAccessPassword()
            );
            
            if (capsule != null) {
                response.put("success", true);
                response.put("data", capsule);
                response.put("message", "胶囊创建成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "胶囊创建失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to create capsule", e);
            response.put("success", false);
            response.put("message", "创建胶囊失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取胶囊详情及其所有条目
     * @param capsuleId 胶囊ID
     * @param authorization JWT令牌
     * @return 胶囊详情
     */
    @GetMapping("/{capsuleId}")
    public ResponseEntity<Map<String, Object>> getCapsuleDetail(
            @PathVariable Long capsuleId,
            @RequestHeader("Authorization") String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            if (capsuleId == null || capsuleId <= 0) {
                response.put("success", false);
                response.put("message", "胶囊ID必须大于0");
                return ResponseEntity.badRequest().body(response);
            }
            
            MemoryCapsule capsule = memoryCapsuleService.getCapsuleById(capsuleId);
            if (capsule == null) {
                response.put("success", false);
                response.put("message", "胶囊不存在");
                return ResponseEntity.notFound().build();
            }
            
            List<MemoryEntry> entries = memoryEntryService.getEntriesByCapsuleId(capsuleId);
            
            Map<String, Object> data = new HashMap<>();
            data.put("capsule", capsule);
            data.put("entries", entries);
            
            response.put("success", true);
            response.put("data", data);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get capsule detail", e);
            response.put("success", false);
            response.put("message", "获取胶囊详情失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新胶囊信息
     * @param capsuleId 胶囊ID
     * @param authorization JWT令牌
     * @param request 更新请求
     * @return 更新结果
     */
    @PutMapping("/{capsuleId}")
    public ResponseEntity<Map<String, Object>> updateCapsule(
            @PathVariable Long capsuleId,
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody CreateCapsuleRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean success = memoryCapsuleService.updateCapsule(
                    capsuleId,
                    request.getTitle(),
                    request.getDescription(),
                    request.getCoverImageUrl(),
                    request.getType(),
                    request.getOpenTime(),
                    request.getAccessPassword()
            );
            
            if (success) {
                response.put("success", true);
                response.put("message", "胶囊更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "胶囊更新失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to update capsule", e);
            response.put("success", false);
            response.put("message", "更新胶囊失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 通过分享码访问胶囊
     * @param shareCode 分享码
     * @param password 访问密码（可选）
     * @return 胶囊信息
     */
    @GetMapping("/share/{shareCode}")
    public ResponseEntity<Map<String, Object>> getCapsuleByShareCode(
            @PathVariable String shareCode,
            @RequestParam(required = false) String password) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            MemoryCapsule capsule = memoryCapsuleService.getCapsuleByShareCode(shareCode);
            if (capsule == null) {
                response.put("success", false);
                response.put("message", "胶囊不存在或已被删除");
                return ResponseEntity.notFound().build();
            }
            if (capsule.getAccessPassword() != null && !capsule.getAccessPassword().isEmpty()) {
                if (!memoryCapsuleService.validateAccessPassword(capsule.getId(), password)) {
                    response.put("success", false);
                    response.put("message", "访问密码错误");
                    return ResponseEntity.badRequest().body(response);
                }
            }
            
            List<MemoryEntry> entries = memoryEntryService.getEntriesByCapsuleId(capsule.getId());
            
            Map<String, Object> data = new HashMap<>();
            data.put("capsule", capsule);
            data.put("entries", entries);
            
            response.put("success", true);
            response.put("data", data);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get capsule by share code", e);
            response.put("success", false);
            response.put("message", "获取胶囊失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 封存胶囊
     * @param capsuleId 胶囊ID
     * @param authorization JWT令牌
     * @return 封存结果
     */
    @PostMapping("/{capsuleId}/seal")
    public ResponseEntity<Map<String, Object>> sealCapsule(
            @PathVariable Long capsuleId,
            @RequestHeader("Authorization") String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean success = memoryCapsuleService.sealCapsule(capsuleId);
            if (success) {
                response.put("success", true);
                response.put("message", "胶囊封存成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "胶囊封存失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to seal capsule", e);
            response.put("success", false);
            response.put("message", "封存胶囊失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 删除胶囊
     * @param capsuleId 胶囊ID
     * @param authorization JWT令牌
     * @return 删除结果
     */
    @DeleteMapping("/{capsuleId}")
    public ResponseEntity<Map<String, Object>> deleteCapsule(
            @PathVariable Long capsuleId,
            @RequestHeader("Authorization") String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean success = memoryCapsuleService.deleteCapsule(capsuleId);
            if (success) {
                response.put("success", true);
                response.put("message", "胶囊删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "胶囊删除失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to delete capsule", e);
            response.put("success", false);
            response.put("message", "删除胶囊失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 添加文本条目到胶囊
     * @param capsuleId 胶囊ID
     * @param authorization JWT令牌
     * @param request 添加请求
     * @return 添加结果
     */
    @PostMapping("/{capsuleId}/entries/text")
    public ResponseEntity<Map<String, Object>> addTextEntry(
            @PathVariable Long capsuleId,
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody AddTextEntryRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            MemoryEntry entry = memoryEntryService.createTextEntry(
                    capsuleId,
                    userId,
                    request.getContent()
            );
            
            if (entry != null) {
                response.put("success", true);
                response.put("data", entry);
                response.put("message", "文本条目添加成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "文本条目添加失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to add text entry", e);
            response.put("success", false);
            response.put("message", "添加文本条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 创建胶囊请求DTO
     */
    public static class CreateCapsuleRequest {
        @NotBlank(message = "标题不能为空")
        @Size(min = 1, max = 100, message = "标题长度必须在1-100之间")
        private String title;
        
        @Size(max = 500, message = "描述长度不能超过500")
        private String description;
        
        @Pattern(regexp = "^https?://.*\\.(jpg|jpeg|png|gif|webp)$", message = "封面图片URL格式不正确")
        private String coverImageUrl;
        
        @NotBlank(message = "类型不能为空")
        @Pattern(regexp = "^(PERSONAL|COUPLE|FAMILY|FRIEND)$", message = "类型必须是PERSONAL、COUPLE、FAMILY或FRIEND")
        private String type;
        
        @Future(message = "开启时间必须是未来时间")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime openTime;
        
        @Size(min = 4, max = 20, message = "访问密码长度必须在4-20之间")
        private String accessPassword;
        
        public String getTitle() {
            return title;
        }
        
        public void setTitle(String title) {
            this.title = title;
        }
        
        public String getDescription() {
            return description;
        }
        
        public void setDescription(String description) {
            this.description = description;
        }
        
        public String getCoverImageUrl() {
            return coverImageUrl;
        }
        
        public void setCoverImageUrl(String coverImageUrl) {
            this.coverImageUrl = coverImageUrl;
        }
        
        public String getType() {
            return type;
        }
        
        public void setType(String type) {
            this.type = type;
        }
        
        public LocalDateTime getOpenTime() {
            return openTime;
        }
        
        public void setOpenTime(LocalDateTime openTime) {
            this.openTime = openTime;
        }
        
        public String getAccessPassword() {
            return accessPassword;
        }
        
        public void setAccessPassword(String accessPassword) {
            this.accessPassword = accessPassword;
        }
    }

    /**
     * 添加文本条目请求DTO
     */
    public static class AddTextEntryRequest {
        @NotBlank(message = "内容不能为空")
        @Size(min = 1, max = 2000, message = "内容长度必须在1-2000之间")
        private String content;
        
        public String getContent() {
            return content;
        }
        
        public void setContent(String content) {
            this.content = content;
        }
    }
}

